const User = require('../models/users')

class usersControllers {
   async find(ctx) {
        ctx.body = await User.find()
    }
   async findById(ctx){
       const User = await User.findById(ctx.params.id)
        if(!User){
            ctx.throw(404,用户不存在)  
        }  else {
            ctx.body = User
        } 
    }
    async create(ctx){
        // 校验字段
        ctx.verifyParams ({
            name:{type: 'string', required: true},
            age: { type: 'number', required: false}
        })
        const user = await User(ctx.request.body).save()
        ctx.body = user
    }
   async update(ctx){
        ctx.verifyParams ({
            name:{type: 'string', required: true},
            age: { type: 'number', required: false}
        })
        const user = await User.findByIdAndUpdate(ctx.params.id,ctx.request.body)
        if(!user) {
            ctx.throw(404)
        } else {
            ctx.body = user
        }
    }
   async delete(ctx){
       const user = await User.findByIdAndDelete(ctx.params.id,ctx.request.body)
       if(!user) {
        ctx.throw(404)
        } else {
            ctx.body = 204
        }
   }
}
module.exports = new usersControllers()